package com.abiao.shop.rabbitmq;

import com.abiao.shop.pojo.DiscountOrder;
import com.abiao.shop.pojo.User;
import com.abiao.shop.service.GoodsService;
import com.abiao.shop.service.OrderService;
import com.abiao.shop.service.SnapService;
import com.abiao.shop.util.TurnUtil;
import com.abiao.shop.vojo.GoodsVo;
import com.abiao.shop.vojo.OrderVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description: SnapMQReceiver 秒杀消息接收服务
 * @Author: AB
 * @Date: 2021-07-21
 * @Version:v1.0
 */
@Service
public class SnapMQReceiver {

    @Autowired
    SnapService snapService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    OrderService orderService;

    /**
     * 监听秒杀消息队列，进行异步处理
     * @param message
     */
    @RabbitListener(queues = SnapMQConfig.SNAP_QUEUE)
    public void receiveSnapMsg(String message){
        SnapMessage snapMessage = TurnUtil.stringToBean(message,SnapMessage.class);
        User user = snapMessage.getUser();
        long goodsId = snapMessage.getGoodsId();
        GoodsVo goodsVo = goodsService.getGoodsVoById(goodsId);
        if (goodsVo.getStockCount()<=0){return;}
        //判断是否已经秒杀过了
        DiscountOrder orderRepeat = orderService.getDCOrderByGoodsIdUserId(user.getId(),goodsId);
        if (orderRepeat!=null){return;}     //重复秒杀
        //减库存，下订单，写入秒杀订单
        OrderVo orderVo = snapService.snapping(snapMessage.getUser(),goodsVo);
        /**
         * 此处没有进行信息返回，前端是使用轮询查看结果，后面优化可以考虑使用 Websocket 实时给用户返回结果
         * 考虑使用 Netty 提高实时通讯性能
         */
    }
}
